﻿#region Copyright(c) 2006 ZO, All right reserved.
// -----------------------------------------------------------------------------
// Copyright(c) 2006 ZO, All right reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   1.  Redistribution of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//   2.  Redistribution in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//   3.  The name of the author may not be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -----------------------------------------------------------------------------
#endregion


#region Using directives

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using ZO.SmartCore.Configuration.Properties;
using ZO.SmartCore.Helpers;
using ZO.SmartCore.IO;
using ArgumentNullException= ZO.SmartCore.Core.ArgumentNullException;
using Version= ZO.SmartCore.Core.Version;

#endregion

namespace ZO.SmartCore.Configuration
{
    /// <summary>
    ///  read and write the <see cref="T:SmartCore.IO.StringStream"/> to the user application location on disk.
    /// </summary>
    public class DecoupledConfigurationProvider : FileConfigurationProvider
    {

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="DecoupledConfigurationProvider"/> class.
        /// </summary>
        public DecoupledConfigurationProvider() : base()
        {
            this._UserPath = GetDataPath(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));

            if (_UserPath.EndsWith(@"\{0}\{1}"))
            {
                _UserPath = StringHelper.Format(_UserPath, "SmartCore Framework 2006", "2.1");
            }

            if (!Directory.Exists(_UserPath))
            {
                Directory.CreateDirectory(_UserPath);
            }

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DecoupledConfigurationProvider"/> class.
        /// </summary>
        /// <param name="name">The name of the Configuration folder which might be the application name.</param>
        /// <param name="version">The version which might be the application version.</param>
        public DecoupledConfigurationProvider(string name, string version)
            : base()
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            if (String.IsNullOrEmpty(version))
            {
                throw new ArgumentNullException("version");
            }

            Version version1 = new Version(version);

            _UserPath = GetDataPath(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));

			if (_UserPath.EndsWith(@"\{0}\{1}"))
			{
                _UserPath = StringHelper.Format(_UserPath, "name", version1.ToString(2));
			}


            if (!Directory.Exists(_UserPath))
            {
                Directory.CreateDirectory(_UserPath);
            }
        }


        #endregion

        #region Destructor

        #endregion

   
        
        #region Fields

        private string _UserPath;
        #endregion

        #region Events

        #endregion

        #region Operators

        #endregion

        #region Properties

        /// <summary>
        /// User Application Path Folder in which Decoupled Storage is stored.
        /// </summary>
        public string UserPath
        {
            get
            {
                return _UserPath;
            }
 
        }
        #endregion

        #region Methods
        /// <summary>
        /// Gets the data path.
        /// </summary>
        /// <param name="basePath">The base path.</param>
        /// <returns></returns>
        private static string GetDataPath(string basePath)
        {
            string text1 = Resources.DecouplePath1;
            string text2 = Resources.DecouplePath2;
            string text3 = Application.CompanyName;
            string text4 = Application.ProductName;
			Version version = new Version(Application.ProductVersion);
			string text5 = version.ToString(2);
            string text6;
            if (text3.Contains(Resources.MicrosoftCorporation))
            {
                text6 = basePath + text2;
            }
            else
            {
                text6 = StringHelper.Format(text1, basePath, text4, text5);
                if (!Directory.Exists(text6))
                {
                    Directory.CreateDirectory(text5);
                }

            }
            return text6;

        }

        #endregion
        #region IConfigurationProvider Members



        /// <summary>
        /// Get The Name of Storage used by the Provider
        /// </summary>
        /// <value>storage name.</value>
        public override string Name
        {
            get
            {
                return "Decoupled";
            }
        }

        /// <summary>
        /// load the file to Stream
        /// </summary>
        /// <param name="file">The name of the file to read from decoupled storage.</param>
        /// <returns>Stream containing the loaded file</returns>
        public override StringStream Load(string file)
        {
            string filePath = Path.Combine(this.UserPath, file);
            return base.Load(filePath);
        }


        /// <summary>
        /// Get Whether specified file exists
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns>true if file exists else false</returns>
        public override bool FileExists(string fileName)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                return false;
            } // if

            fileName = Path.Combine(this.UserPath, fileName);
            return File.Exists(fileName);
        }

        /// <summary>
        /// Get Whether specified directory exists
        /// </summary>
        /// <param name="directoryName">Name of the directory.</param>
        /// <returns>true if directory exists else false</returns>
        public override bool DirectoryExists(string directoryName)
        {
            if (String.IsNullOrEmpty(directoryName))
            {
                return false;
            } // if

            directoryName = Path.Combine(this.UserPath, directoryName);
            return Directory.Exists(directoryName);
        }

        /// <summary>
        /// Gets all the files names in specified folder.
        /// </summary>
        /// <param name="directoryName">Name of the directory.</param>
        /// <returns>All files name in specified folder</returns>
        public override string[] GetFilesNames(string directoryName)
        {
            List<string> list = new List<string>();

            if (String.IsNullOrEmpty(directoryName))
            {
                return list.ToArray();
            } // if

            directoryName = Path.Combine(this.UserPath, directoryName);

            if (Directory.Exists(directoryName))
            {
                string[] directories = Directory.GetFiles(directoryName, "*", SearchOption.TopDirectoryOnly);

                foreach (string file in directories)
                {
                    list.Add(file);
                }
            }


            return list.ToArray();
        }


        /// <summary>
        /// Gets all the files names in specified folder.
        /// </summary>
        /// <param name="directoryName">Name of the directory.</param>
        /// <param name="searchPattern">The search string to match against the names of files in path.</param>
        /// <returns>All files name in specified folder</returns>
        public override string[] GetFilesNames(string directoryName, string searchPattern)
        {
            List<string> list = new List<string>();

            if (String.IsNullOrEmpty(directoryName))
            {
                return list.ToArray();
            } // if

            directoryName = Path.Combine(this.UserPath, directoryName);

            if (Directory.Exists(directoryName))
            {

                foreach (string file in Directory.GetFiles(directoryName, searchPattern, SearchOption.TopDirectoryOnly))
                {
                    list.Add(file);
                }
            }

            return list.ToArray();
        }


        /// <summary>
        /// load the file to Stream
        /// </summary>
        /// <param name="folderPath">The realtive folder path from which folder is loaded.</param>
        /// <param name="file">The name of the file to read from decoupled storage.</param>
        /// <returns>Stream containing the loaded file</returns>
        public virtual StringStream Load(string folderPath, string file)
        {
            string filePath = Path.Combine(Path.Combine(this.UserPath, folderPath), file);
            return base.Load(filePath);
        }

        /// <summary>
        /// Saves the specified configuration.
        /// </summary>
        /// <param name="file">The file name to save.</param>
        /// <param name="contents">The contents.</param>
        public override void Save(string file, StringStream contents)
        {
            string filePath = Path.Combine(this.UserPath, file);
            base.Save(filePath, contents);         
        }

        /// <summary>
        /// Saves the specified configuration.
        /// </summary>
        /// <param name="folderPath">The folder path from which folder is loaded.</param>
        /// <param name="file">The file name to save.</param>
        /// <param name="contents">The contents.</param>
        public virtual void Save(string folderPath, string file, StringStream contents)
        {
            string filePath = Path.Combine(Path.Combine(this.UserPath, folderPath), file);
            base.Save(filePath, contents);
        }

        /// <summary>
        /// Creates the directory.
        /// </summary>
        /// <param name="directory">The path of the directory to create.</param>
        public override void CreateDirectory(string directory)
        {
            string directoryPath = Path.Combine(this.UserPath, directory);
            base.CreateDirectory(directoryPath);
        }

        /// <summary>
        /// Deletes the directory.
        /// </summary>
        /// <param name="directory">The directory.</param>
        public override void DeleteDirectory(string directory)
        {
            string directoryPath = Path.Combine(this.UserPath, directory);
            base.DeleteDirectory(directoryPath);
        }

        /// <summary>
        /// Deletes the File.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        public override void DeleteFile(string fileName)
        {
            string filePath = Path.Combine(this.UserPath, fileName);
            base.DeleteFile(filePath);

        }

        #endregion
    }
}
